import React from "react";
import { formatMessage } from 'umi-plugin-react/locale';
import { Button, Form, Input, Modal, Select, Tooltip, Icon, Steps, Checkbox, Radio, Upload } from "antd";
import styles from "./robotAdd.less";
import UserSession from "@/UserSession";

const { Step } = Steps;

class RobotAdd extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      buttonLoading: false,
      stepType: 0,
      channel: null,
      infoData: null,

      avatar: "",
      loading: false,
    };
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  setButtonLoading = (status) => {
    this.setState({ buttonLoading: status });
  };

  cancelModal = () => {
    const { form } = this.props;
    this.setState({
      buttonLoading: false,
      stepType: 0,
      infoData: null,
    });
    form.resetFields();
    this.props.closeAdd();
  };

  onSubmit = () => {
    const { infoData, avatar } = this.state;
    const { form } = this.props;
    form.validateFields((errors, values) => {
      if (!errors) {
        this.setState({ buttonLoading: true }, () => {
          console.log(infoData, values);
          let applicationInfo = {
            name: values.applicationName,
            introduction: values.introduction,
          };
          if (avatar && avatar !== '') {
            applicationInfo.imgUrl = avatar;
          } else {
            form.setFields({ avatar: { errors: [new Error(formatMessage({ id: 'robotAdd.avatarRequired' }))], } });
            return;
          };
          this.props.addRobot(applicationInfo);
        });
      }
    });
  };

  checkName = (rule, value, callback) => {
    if (value && value.length > 20) {
      callback(formatMessage({ id: 'robotAdd.nameMaxLength' }));
    } else {
      callback();
    }
  };

  nextStep = () => {
    const { form } = this.props;
    form.validateFields((err, values) => {
      if (!err) {
        this.setState({ stepType: 1, channel: values?.applicationPlatform, infoData: values });
      }
    });
  };

  previousStep = () => {
    const { infoData } = this.state;
    this.setState({ stepType: 0 }, () => {
      this.props.form.setFieldsValue(infoData);
    });
  };

  setModule = e => {
    this.props.form.setFieldsValue({ module: ['robot'] })
  }

  render() {
    const { visible } = this.props;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { buttonLoading, stepType, channel, avatar } = this.state;
    const uploadButton = (
      <div style={{ border: '#E8E8E8 1px solid', padding: '14px 7px', textAlign: 'center', background: '#FAFAFA',cursor:"pointer" }}>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">{formatMessage({ id: 'robotAdd.uploadFile' })}</div>
      </div>
    );

    return (
      <Modal
        title={formatMessage({ id: 'robotAdd.title' })}
        visible={visible}
        onCancel={this.cancelModal}
        okButtonProps={{ loading: buttonLoading }}
        width={850}
        footer={[
          <Button type='primary' onClick={this.cancelModal}>{formatMessage({ id: 'common.cancel' })}</Button>,
          <Button type='primary' onClick={this.onSubmit}>{formatMessage({ id: 'common.confirm' })}</Button>,
        ]}
        destroyOnClose
        bodyStyle={{ padding: 0 }}
      >
        <img style={{ width: '100%' }} src={staticPath + "/robotAddBg.jpg"} />
        <div className={styles.stepBox}>
          <div style={{ color: '#3E5BFF' }}>
            <Icon type="edit" style={{ marginRight: 10 }} />
            <span>{formatMessage({ id: 'robotAdd.fillInfo' })}</span>
          </div>
        </div>
        <Form layout="vertical" style={{ width: '90%', margin: '0 auto' }}>
          <Form.Item label={formatMessage({ id: 'robotAdd.nameLabel' })}>
            {getFieldDecorator("applicationName", {
              rules: [
                { required: true, message: formatMessage({ id: 'robotAdd.nameRequired' }) },
                { validator: this.checkName },
              ],
            })(<Input placeholder={formatMessage({ id: 'robotAdd.namePlaceholder' })} maxLength={20} />)}
          </Form.Item>
          <div style={{ display: 'flex', width: '100%', gap: '16px' }}>
            <Form.Item label={formatMessage({ id: 'robotAdd.introLabel' })} style={{ flex: 1, marginBottom: 8 }}>
              {getFieldDecorator('introduction', { rules: [{ required: true, message: formatMessage({ id: 'robotAdd.introRequired' }) }], })(<Input.TextArea rows={3} placeholder={formatMessage({ id: 'robotAdd.introPlaceholder' })} />)}
            </Form.Item>
            <Form.Item label={formatMessage({ id: 'robotAdd.avatarLabel' })} style={{ marginBottom: 8 }}>
              <span className={styles['default-img-ul']}>
                {getFieldDecorator("avatar", {
                  valuePropName: "url",
                  rules: [{ required: true }],
                  getValueFromEvent: this.normFile,
                })(
                  <Upload
                    name='file'
                    listType='picture'
                    showUploadList={false}
                    action='/cloud/file/upload'
                    beforeUpload={this.beforeUpload}
                    onChange={(info) => this.handleChangeImage(info, "avatar")}
                    accept='.png,.jpg,.gif,.svg'
                  >
                    {avatar && avatar !== '' ? (
                      <div
                        style={{
                          width: '72px',
                          height: '72px',
                          fontSize: '0px',
                          lineHeight: '72px',
                          textAlign: 'center',
                          border: '#3e5bff 1px solid',
                          background: '#f0f5ff',
                          cursor:"pointer"
                        }}
                      >
                        <img src={fileUrl + avatar} alt='file' style={{ maxWidth: 70, maxHeight: 70 }} />
                      </div>
                    ) : uploadButton}
                  </Upload>
                )}
              </span>
            </Form.Item>
          </div>
        </Form>
      </Modal>
    );
  }

  normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  handleChangeImage = (file, type) => {
    if (file.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    };
    if (file.file.status === "done") {
      this.setState({
        [type]: file.file.response.url,
        loading: false,
      });
    }
  };

  /**
   * 上传图片前判断
   * @returns {*}
   */
  beforeUpload = (file) => {
    let b = /\.(png|jpg|gif|svg)$/;
    let a = file.name.toLowerCase();

    const pig = b.test(a);
    const isJPG = file.type;
    const isLt2M = file.size / 1024 / 1024 < 200;

    if (!pig) {
      if (!isLt2M) {
        message.error(formatMessage({ id: 'robotAdd.imageSizeError' }));
      } else {
        message.error(formatMessage({ id: 'robotAdd.imageFormatError' }));
      }
    } else {
      if (!isLt2M) {
        message.error(formatMessage({ id: 'robotAdd.imageSizeError' }));
      }
    };
    return isJPG && isLt2M && pig;
  };

  setImgUrl = (row, type) => {
    this.setState({ [type]: row.url });
  }
}

export default Form.create()(RobotAdd);
